package br.com.massai.model.dao;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;

import br.com.massai.model.entity.Function;
import br.com.massai.model.entity.Module;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.enums.Functionality;

@Stateless
@SuppressWarnings({ "rawtypes" , "unchecked" })
public class FunctionDAO extends GenericDAO<Function> implements FunctionRepository {

	private static final long serialVersionUID = -2206334745375210340L;
	@EJB private GenericRepository genericRepository;

	@Override
	public Function getFunctionByAcronym(String acronym) throws SystemException {
		try  {
			return (Function) em.createQuery("SELECT f FROM Function f WHERE f.acronym =:acronym").setParameter("acronym", acronym).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public List<Function> findAllOrdered() throws SystemException {
		return em.createQuery("SELECT f FROM Function f ORDER BY f.description").getResultList();
	}

	@Override
	public List<Function> findOrderedByFunctionality(Functionality functionality) throws SystemException {
		genericRepository.setEntity(Module.class);
		Module module = (Module) genericRepository.findID(functionality.getCode());
		return em.createQuery("SELECT f FROM Function f WHERE f.module =:module ORDER BY f.description").setParameter("module", module).getResultList();
	}

	@Override
	public List<Function> findByModule(Module module) throws SystemException {
		return em.createQuery("SELECT f FROM Function f WHERE f.module =:module ORDER BY f.description").setParameter("module", module).getResultList();
	}
}